#include "oseventthread.h"
#include <QApplication>
#include <QDebug>
#include <QEvent>
#include <QWidget>
#include <QKeyEvent>
#include <QSharedMemory>
#include <QBuffer>

#ifdef __linux
#include <linux/input.h>
#endif
#include <fcntl.h>
#include <unistd.h>

OSEventThread::OSEventThread(QObject *parent) :
    QThread(parent)
{
    stopped = false;
#ifndef __linux
    m_sharedMemory = new QSharedMemory("1");
#endif

}

void OSEventThread::stop()
{
    QMutexLocker locker(&m_lock);
    stopped = true;
}

void OSEventThread::run()
{
#ifdef __linux
INIT:
    int keys_fd;
    struct input_event t;
    keys_fd = open("/dev/input/event0", O_RDONLY);
    if (keys_fd <= 0)
    {
        qWarning("remote control open error");
        sleep(1);
        goto INIT;
        return;
    }

    while (!stopped)
    {
        if (read(keys_fd, &t, sizeof(t)) == sizeof(t))
        {
            if (t.type == EV_KEY && (t.value == 0))
            {
                qDebug("%d,%d:%s", t.code, t.value,t.value ? "press":"release");
                emit keySignal(t.code, t.value);
            }
        }
        else
        {
            goto INIT;
        }
    }
#else

    while(!stopped)
    {
        if (!m_sharedMemory->isAttached())
        {
            if (!m_sharedMemory->attach())
            {
                continue;
            }
        }

        QBuffer buffer;
        m_sharedMemory->lock();
        buffer.setData((char*)m_sharedMemory->constData(), m_sharedMemory->size());
        buffer.open(QBuffer::ReadOnly);
        QString data = buffer.readAll();
        if (data.isEmpty())
        {
            m_sharedMemory->unlock();
            continue;
        }
        memset(m_sharedMemory->data(),0,1024);
        m_sharedMemory->unlock();
        m_sharedMemory->detach();

        emit keySignal(data.toInt(),0);
    }


#endif
}



